package com.work.formaldehyde.orderfragment;

import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.google.gson.Gson;
import com.wang.avi.AVLoadingIndicatorView;
import com.work.formaldehyde.R;
import com.work.formaldehyde.activity.CheckWuLiuActivity;
import com.work.formaldehyde.activity.DingDanXiangQingActivity;
import com.work.formaldehyde.activityadapter.AllDingDanAdapter;
import com.work.formaldehyde.activityadapter.DaiPingJiaAdapter;
import com.work.formaldehyde.activityadapter.DaiShouHuoAdapter;
import com.work.formaldehyde.model.AllDingDanModel;
import com.work.formaldehyde.model.DPJDingDanModel;
import com.work.formaldehyde.model.DSHDingDanModel;
import com.work.formaldehyde.util.ApiUtils;
import com.work.formaldehyde.util.Url;
import com.work.formaldehyde.wxapi.WXPayEntryActivity;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class DSHFragment extends Fragment implements View.OnClickListener, DaiShouHuoAdapter.DetailViewHolderListener {
    //用于获取视图
    private View root;
    private ListView daishouhuolist;
    public static AVLoadingIndicatorView loding_avi;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.fragment_daishouhuo, container, false);//初始加载
        if (ApiUtils.isNetworkConnected(getActivity()))
            InitView(root);
        return root;
    }

    public static ArrayList<AllDingDanModel.data> new_list_views;
    public static DaiShouHuoAdapter myAdapters;

    public void Init() {
        new_list_views = new ArrayList<>();
        myAdapters = new DaiShouHuoAdapter(new_list_views,
                getActivity(), this);
        daishouhuolist.setAdapter(myAdapters);
        okHttp_postFromParameters1();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (WXPayEntryActivity.wxpay_s1) {
            okHttp_postFromParameters1();
        }
    }

    @Override
    public void onStart() {
        super.onStart();

    }

    /**
     * 初始加载视图
     */
    public void InitView(View view) {
        loding_avi = view.findViewById(R.id.loding_avi);
        loding_avi.show();
        daishouhuolist = view.findViewById(R.id.daishouhuolist);
        Init();
        daishouhuolist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent tokpxq = new Intent(getActivity(), DingDanXiangQingActivity.class);
                tokpxq.putExtra("position", position + "");
                tokpxq.putExtra("username", new_list_views.get(position).getUser_name());
                tokpxq.putExtra("userphone", new_list_views.get(position).getUser_phone());
                tokpxq.putExtra("address", new_list_views.get(position).getUser_address());
                tokpxq.putExtra("ispay", new_list_views.get(position).getIspay());
                tokpxq.putExtra("type", "2");
                if (new_list_views.get(position).getGoods().size() > 1)
                    tokpxq.putExtra("duoge", "true");
                else
                    tokpxq.putExtra("duoge", "false");
                tokpxq.putExtra("shangpingimg", new_list_views.get(position).getGoods().get(0).getGoods_img());
                tokpxq.putExtra("shangpingname", new_list_views.get(position).getGoods().get(0).getGoods_name());
                tokpxq.putExtra("shangpingnum", new_list_views.get(position).getGoods().get(0).getGoods_num());
                tokpxq.putExtra("shangpingzongjia", new_list_views.get(position).getGoods().get(0).getGoods_discount_price());
                tokpxq.putExtra("dingdannum", new_list_views.get(position).getOrder_number());
                tokpxq.putExtra("xiadanshijian", new_list_views.get(position).getCreate_time());
                tokpxq.putExtra("zhifufangshi", new_list_views.get(position).getPay_type());
                tokpxq.putExtra("zhifushijian", new_list_views.get(position).getPay_time());
                tokpxq.putExtra("tuihuo", new_list_views.get(position).getOrder_status());
                startActivity(tokpxq, ActivityOptions.makeSceneTransitionAnimation(getActivity()).toBundle());
            }
        });
    }

    private int postion = 0;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
        }
    }

    public static void okHttp_postFromParameters1() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
//                    RequestBody formBody = new FormBody.Builder()
//                            .add("uid", Url.USER_ID).add("status", "1").build();
//                    Request request = new Request.Builder().url(Url.GETDINGDANLIST).post(formBody).build();
//                    okhttp3.Response response = okHttpClient.newCall(request).execute();
//                    String msg = response.body().string();
//                    Message message = new Message();
//                    message.obj = msg;
//                    gethot.sendMessage(message);
                    Request request = new Request.Builder().get().url(Url.ADDDINGDANS+"?uid="+ Url.USER_ID + "&logintoken=" + Url.LOGIN_TOKEN+"&status=1").build();
                    Call call = okHttpClient.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                        }

                        @Override
                        public void onResponse(Call call, final Response response) {
                            try {
                                final String responseStr;
                                responseStr = response.body().string();
                                Message message = new Message();
                                message.obj = responseStr;
                                gethot.sendMessage(message);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    public static AllDingDanModel allDingDanModel;
    public static Handler gethot = new Handler() {
        public void handleMessage(android.os.Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    ApiUtils.SetLog("dsh:"+msg.obj.toString());
                    loding_avi.hide();
                    ApiUtils.SetLog("msg:"+msg.obj.toString());
                    ApiUtils.closepopup();
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        Gson gson = new Gson();
                        allDingDanModel = gson.fromJson(msg.obj.toString(),
                                AllDingDanModel.class);
                        new_list_views.clear();
                        new_list_views.addAll(allDingDanModel.getData());
                        Collections.reverse(new_list_views);
                        myAdapters.notifyDataSetChanged();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    public void setData(DaiShouHuoAdapter.init viewHolder, final int position) {
        viewHolder.chakanwuliu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent toaddress = new Intent(getActivity(), CheckWuLiuActivity.class);
                ordnum = new_list_views.get(position).getOrder_number();
                toaddress.putExtra("dingdanhao", ordnum);
                toaddress.putExtra("shangpingname", new_list_views.get(position).getGoods().get(0).getGoods_name());
                toaddress.putExtra("imgurl", new_list_views.get(position).getGoods().get(0).getGoods_img());
                startActivity(toaddress, ActivityOptions.makeSceneTransitionAnimation(getActivity()).toBundle());
            }
        });
        viewHolder.querenshouhuo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ordnum = new_list_views.get(position).getOrder_number();
                postion = position;
                windowiss(getActivity(), daishouhuolist);
            }
        });
    }

    private static PopupWindow popupWindows;

    public void windowiss(Context context, View view) {
        View popupwindowviews = null;
        popupwindowviews = LayoutInflater.from(context).inflate(
                R.layout.popup_qrsh, null);
        RelativeLayout dangqian = popupwindowviews.findViewById(R.id.dangqian);
        dangqian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ApiUtils.windows(getActivity(), daishouhuolist, "正在确认");
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        ApiUtils.closepopup();
                    }
                }, 10000);
                okHttp_Del();
                popupWindows.dismiss();
            }
        });
        RelativeLayout jieshu = popupwindowviews.findViewById(R.id.jieshu);
        jieshu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindows.dismiss();
            }
        });
        popupWindows = new PopupWindow(popupwindowviews, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindows.setAnimationStyle(R.style.popwin_anim_style);
        popupWindows.setTouchable(true);
        popupWindows.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // TODO Auto-generated method stub
                WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                lp.alpha = 1f;
                getActivity().getWindow().setAttributes(lp);
            }
        });
        popupWindows.setFocusable(true);
        popupWindows.setOutsideTouchable(true);
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = 0.4f;
        getActivity().getWindow().setAttributes(lp);
        popupWindows.showAtLocation(view, Gravity.BOTTOM, 0, 0);
    }

    public String ordnum = "";

    private void okHttp_Del() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody formBody = null;
                    Request request;
                    formBody = new FormBody.Builder()
                            .add("uid", Url.USER_ID).add("logintoken", Url.LOGIN_TOKEN).add("order_number", ordnum).build();
                    request = new Request.Builder().url(Url.QUERENSHOUHUOS).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    getdel.sendMessage(message);
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    public Handler getdel = new Handler() {
        public void handleMessage(android.os.Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    ApiUtils.closepopup();
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        new_list_views.remove(postion);
                        myAdapters.notifyDataSetChanged();
//                        ApiUtils.windows(getActivity(), daishouhuolist, "请稍后");
//                        new Handler().postDelayed(new Runnable() {
//                            public void run() {
//                                ApiUtils.closepopup();
//                            }
//                        }, 10000);
//                        okHttp_postFromParameters1();
//                        okHttp_postFromParameters1();
                        AllFragment.okHttp_postFromParameters1();
                        DPJFragment.okHttp_postFromParameters1();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
}